<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/10
 * Time: 9:47
 */

namespace App\Http\Controllers\Home;

use \App\Http\Controllers\Controller;
use App\Model\Apply;
use App\Model\Branch;
use App\Model\ExceedShop;
use App\Model\FieldActivities;
use App\Model\IdentityVerification;
use App\Model\Members;
use App\Model\MembersLevel;
use App\Model\MicroMall;
use App\Model\RecordBonus;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use Session;
use Cookie;

class LoginController extends Controller
{
    /**
     * 系统升级
     */
    public function upgrade()
    {
        return view('Home.index');
    }

    /**
     * login
     */
    public function getLogin(Request $request)
    {
//        return view('Home.index');
        //不用直接登录
        if (!empty($request->get('cookie') && $request->get('cookie') == "no" && !empty($_COOKIE['remember']))) {
            setcookie('remember', 0, time() - 1);
//            return view('Home.login.login');
        }
//        if (!empty($_COOKIE['remember'])){
//            $user = Members::where(['uid' => $_COOKIE['remember']])->first();
//            Session::put('home_user', $user);
//            return redirect('/home/member/index')->withErrors('登录成功');
//        }
        return view('Home.login.login');
    }

    public function login(Request $request)
    {
        $data = $request->all();
        //记住密码字段
        $remember = request('remember');
        //闪存
        $request->session()->flash('name', $data['name']);
        //获取验证码
//        if (Session::get('milkcaptcha') != $data['captcha']) {
//            return redirect()->back()->withErrors('验证码输入错误！');
//        }
        if (empty($data['name'])) {
            return ['code' => 0, 'data' => '请输入账户名或电话号码'];
        }
        if (empty($data['password'])) {
            return ['code' => 0, 'data' => '请输入账户密码'];
        }
        //去掉空格
        $name = preg_replace('# #', '', $data['name']);
        $password = $data['password'];
        //用户输入验证码正确
        $user = Members::where(['name' => $name])->first();
        $total = RecordBonus::where('uid', $user['uid'])->sum('money');
//        $credit3 = $user['credit3'] - $user['consumption_bonus'];
        if ($user['registered'] == 0) {
            return \Redirect::back()->withErrors("此账户暂无登录权限，请联系管理员！！");

        }
        if (!empty($user)) {
            if (ENCRYPTION($password, $user->salting) == $user->password) {
                $salting = RANDOM();
                $userData = [
                    'ip' => $_SERVER["REMOTE_ADDR"],
                    'password' => ENCRYPTION($password, $salting),
                    'salting' => $salting,
                    'sign_in' => time(),
                    'session_id' => Session::getId(),
//                    'credit3' => $credit3,
                    'share_voucher' => $total,
                ];
//                if ($user['isdown'] == 1) { //超级商城
//                    if ($data['name'] != '15884158619') {
//                        if ($user['credit3'] >= 500 && $user['is_credit3'] <= 3) { //微商城
//                            $user['is_credit3'] += 1;
//                            $userData['is_credit3'] = $user['is_credit3'];
//                        }
//                    }
//                }
                $MemberLevel = MembersLevel::where('id', $user['level'])->first();
//                if ($user['straight_shop_isdown'] == 1 && $user['level'] >= 1) {
//                    if ($data['name'] != '15884158619') {
//                        if ($user['credit6'] >= $MemberLevel['credit3'] && $user['is_credit6'] <= 3) {//直商城
//                            $user['is_credit6'] += 1;
//                            $userData['is_credit6'] = $user['is_credit6'];
//                        }
//                    }
//                }
                $rico = Members::where(['uid' => $user->uid])->update($userData);
                if ($rico) {
                    //保存session
                    Session::put('home_user', $user);
                    if ($name == $password) {
                        $instructions = '账号登录密码及支付密码不安全,请及时修改！';
                    } else {
                        if ($user['credit3'] >= 500) {
                            $instructions = '超级商城达到复投标准请复投，警告三次之后就不产生任何收益。';
                        } else {
                            $instructions = '登录成功！';
                        }
                    }

                    if (!empty($remember)) {
                        setcookie('remember', $user->uid, time() + 60 * 60 * 24 * 3);
                    }
                    return redirect('/home/excellent/index')->withErrors($instructions);
                } else {
                    return \Redirect::back()->withErrors("登录失败！");
                }
            } else if ($password == $user->password) {
                $userData = [
                    'ip' => $_SERVER["REMOTE_ADDR"],
                    'password' => $user->password,
                    'salting' => $user->salting,
                    'sign_in' => time(),
                    'session_id' => Session::getId(),
//                    'credit3' => $credit3,
                    'share_voucher' => $total,
                ];
//                if ($user['isdown'] == 1) { //超级商城
//                    if ($data['name'] != '15884158619') {
//                        if ($user['credit3'] >= 500 && $user['is_credit3'] <= 3) { //微商城
//                            $user['is_credit3'] += 1;
//                            $userData['is_credit3'] = $user['is_credit3'];
//                        }
//                    }
//                }
                $MemberLevel = MembersLevel::where('id', $user['level'])->first();
//                if ($user['straight_shop_isdown'] == 1 && $user['level'] >= 1) {
//                    if ($data['name'] != '15884158619') {
//                        if ($user['credit6'] >= $MemberLevel['credit3'] && $user['is_credit6'] <= 3) {//直商城
//                            $user['is_credit6'] += 1;
//                            $userData['is_credit6'] = $user['is_credit6'];
//                        }
//                    }
//                }
                $rico = Members::where(['uid' => $user->uid])->update($userData);
                if ($rico) {
                    //保存session
                    Session::put('home_user', $user);
                    if ($user['credit3'] >= 500) {
                        $instructions = '新人专区达到复投标准请复投，警告三次之后就不产生任何收益。';
                    } else {
                        $instructions = '登录成功！';
                    }
                    if (!empty($remember)) {
                        setcookie('remember', $user->uid, time() + 60 * 60 * 24 * 3);
                    }
                    return redirect('/home/excellent/index')->withErrors($instructions);
                } else {
                    return \Redirect::back()->withErrors("登录失败！");
                }
            } else {
                return \Redirect::back()->withErrors("登录失败！");
            }
        } else {
            return \Redirect::back()->withErrors("登录失败！");
        }
    }

    /**
     * 错误展示页面
     */
    public function error()
    {
        return view('Home.error');
    }

    public function impro()
    {
        //代理商数据修改
        $res = DB::table('wenjian_users')->get();
        $user = Members::where('activation_time', '<', 1533139200)->select('name', 'original_money')->get();
        $num = 0;
        foreach ($res as $key => $value) {
            foreach ($user as $k => $v) {
                if ($value->users == $v->name) {
                    $data['original_money'] = $value->qjb;
                    Members::where(['name' => $value->users])->update($data);
                }

            }
//            if($value->users == $user['name']){
//                $data['performance_a'] = $value->zqu+$user['performance_a'];
//                $data['performance_b'] = $value->yqu+$user['performance_b'];
//                Members::where(['name'=>$value->users])->update($data);
//            }
        }

//        $res = Members::select('uid','phone','name')->get();
//        foreach ($res as $value){
//            $data['phone'] = $value['name'];
////            dump($data);
//            Members::where('uid',$value['uid'])->update($data);
//        }
    }

    //显示记住密码
    public function remember(Request $request)
    {
        $cookie = request('cookie');
        if (empty($cookie)) {
            return [
                'code' => 0,
                'data' => '自动保存已过期'
            ];
        }
        $me = Members::where('uid', $cookie)->select('name', 'password')->first();
        return $me;
    }

    /**
     * @param Request $request
     * @return array
     * 实名认证
     */
    public function realName(Request $request)
    {
        $data = $request->all();
        $user = session('home_user');
        if (!$data['recharge_money']) {
            return ['code' => 0, 'data' => '充值金额不能为空'];
        }
        //查找是否提交过数据
        $record = IdentityVerification::where(['name' => $user['name'], 'status' => 0])->first();
        if ($record) {
            return ['code' => 0, 'data' => '请勿重复提交'];
        }
//        $data = Members::where('name', $datas['name'])->select('uid', 'user_name')->first();
//        if (empty($data)) {
//            return ['code' => 0, 'data' => '账号不存在,请重新输入'];
//        }
        if (empty($_FILES)) {
            return ['code' => 0, 'data' => '请上传凭证'];
        }
        //图片上传到本地
        $iamge = $this->image();
//        var_dump($iamge);exit;
        if ($iamge['code'] == 0) {
            return ['code' => 0, 'data' => $iamge['data']];
        }
        if (empty($iamge['data']['thumb'])) {
            return ['code' => 0, 'data' => '图片上传失败'];
        }
        $data['front_id_card'] = $iamge['data']['image'];

        //拼装数据
        $member = [
            'number' => ORDER_SN(),
            'name' => $user['name'],
            'user_name' => $user['user_name'],
            'recharge_money' => $data['recharge_money'],
            'front_id_card' => $_SERVER['HTTP_ORIGIN'] . '/'.'img/admin/'.$data['front_id_card'],
            'uid' => $user['uid'],
            'status' => 0,
            'created_at' => date('Y-m-d H:i:s'),
        ];
//        var_dump($member);exit;
        $res = IdentityVerification::create($member);
        if ($res) {
            return ['code' => 1, 'data' => '提交成功'];
        } else {
            return ['code' => 0, 'data' => '提交失败,请稍后再试'];
        }

    }

    /**
     * 图片上传
     * @param string $folder
     * @return array
     */
    public function image($folder = 'home')
    {
        $allowedExts = array("jpeg", "jpg", "png");
        $temp = explode(".", $_FILES["file"]["name"]);
        $extension = end($temp);        // 获取文件后缀名
        if ((($_FILES["file"]["type"] == "image/gif")
                || ($_FILES["file"]["type"] == "image/jpeg")
                || ($_FILES["file"]["type"] == "image/jpg")
                || ($_FILES["file"]["type"] == "image/pjpeg")
                || ($_FILES["file"]["type"] == "image/x-png")
                || ($_FILES["file"]["type"] == "image/png"))
            && ($_FILES["file"]["size"] < 5242880)    // 小于 5M
            && in_array($extension, $allowedExts)) {
            if ($_FILES["file"]["error"] > 0) {
                return ['code' => 0, 'data' => '错误：' . $_FILES["file"]["error"]];
            } else {
                $url = '/public/img/admin/';
                if (!is_dir(base_path() . $url)) {
                    mkdir(base_path() . $url, 0777, true);
                }
                $imgName = 'shenfenzhen-' . time() . rand(100, 999) . '.jpg';
                $urlNaem = move_uploaded_file($_FILES["file"]["tmp_name"], base_path() . $url . $imgName);
//                var_dump(base_path());exit;
                if ($urlNaem) {
                    return ['code' => 1, 'data' => [
                        'thumb' => $url . $imgName,
                        'image' => $imgName
                    ]];
                } else {
                    return ['code' => 0, 'data' => '上传失败'];
                }
            }
        } else {
            return ['code' => 0, 'data' => '格式错误'];
        }
    }

    /**
     * 实名认证
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function realNameAuthentication()
    {
        return view('Home.login.authentication');
    }

    //会员注册页面
    public function registerView()
    {

        return view('Home.login.register');
    }

    public function register(Request $request)
    {
        $data = $request->all();
        //会员表
        $MemberModel = new Members();
        //判断联系人
        if (empty($data['phone'])) {
            return ['code' => 0, 'data' => '联系人电话不能为空'];
        };
        // 检测手机号格式
        if (!preg_match('/^1[356789]\d{9}$/', $data['phone'])) {
            return ['code' => 0, 'data' => '请填写正确的手机号'];
        }
        //判断联系人姓名
        if (empty($data['name'])) {
            return ['code' => 0, 'data' => '联系人姓名不能为空'];
        };
        //判断分享人电话
        if (empty($data['referrer'])) {
            return ['code' => 0, 'data' => '分享人电话不能为空'];
        };
        //会员表
        $UserModel = new Members();
        //判断分享人是否存在
        $referrer = $UserModel->where(['phone' => $data['referrer']])->first();
        if (empty($referrer)) {
            return ['code' => 0, 'data' => '分享人不存在'];
        }
        //判断用户电话是否注册
        $phone = $UserModel->where(['phone' => $data['phone']])->count();
        if (!empty($phone)) {
            return ['code' => 0, 'data' => '电话已被注册'];
        }
        //微商城设置
        $microMall = new MicroMall();
        $micro = $microMall->orderBy('sorting')->first();
        //超级商城设置
        $ExceedShopModel = new ExceedShop();
        $ExceedShop = $ExceedShopModel->get()->toArray();
        $random = RANDOM(); //秘钥
        $memberData = [
            'name' => $data['phone'],
            'user_name' => $data['name'],
            'phone' => $data['phone'],
            'password_pay' => ENCRYPTION(empty($data['password_pay']) ? $data['phone'] : $data['password_pay'], $random),
            'password' => ENCRYPTION(empty($data['password']) ? $data['phone'] : $data['password'], $random),
            'salting_pay' => $random,
            'salting' => $random,
            'enroll_time' => time(), //注册时间
            'activation_time' => time(), //激活时间
            'registered' => 1, //1 已激活 0 未激活
//            'company_id' => $company_id, //公司id
            'tiny_level' => $micro['id'],
            'referrer' => $referrer['uid'], //分享人
            'straight_shop_isdown' => $referrer['straight_shop_isdown'], //直商城开关 1开 2关
            'feferrer_name' => $referrer['user_name'], //分享人姓名
            'tiny_level_name' => $micro['vip_name'],
            'aisle' => 1, // 1 报单商城
            'super_level' => 1, //报单商城等级
            'super_level_name' => $ExceedShop[0]['vip_name'], //报单商城等级 名称
            'stores_number' => 0, //门店中心编号
            'updated_at' => date('Y-m-d H:i:s'),
            'created_at' => date('Y-m-d H:i:s')
        ];
//        var_dump($memberData);exit;
        $member = $UserModel->create($memberData);
        if (empty($member)) {
            DB::rollback();  //回滚
            return ['code' => 0, 'data' => '注册失败,重新注册'];
        } else {
            return ['code' => 1, 'data' => '注册成功，即可登录'];
        }
//        switch ($data['class']){
//            case'referrer':
//                $recipient = $MemberModel->find_members(['phone' => $data['user']['phone']], ['uid', 'phone', 'user_name']);
//                if (empty($recipient)) {
//                    return ['code' => 0, 'data' => '没有对方数据'];
//                } else {
//                    $recipient['user_name'] = empty($recipient['user_name']) ? $recipient['phone'] : $recipient['user_name'];
//                    return ['code' => 1, 'data' => $recipient];
//                }
//                break;
//            case 'add_member':
//                //判断联系人
//                if (empty($data['phone']) ) {
//                    return ['code' => 0, 'data' => '联系人电话不能为空'];
//                };
//                // 检测手机号格式
//                if (!preg_match('/^1[356789]\d{9}$/', $data['phone'])) {
//                    return ['code' => 0, 'data' => '请填写正确的手机号'];
//                }
//                //判断联系人姓名
//                if (empty($data['name'])) {
//                    return ['code' => 0, 'data' => '联系人姓名不能为空'];
//                };
//                //判断分享人电话
//                if (empty($data['referrer'])) {
//                    return ['code' => 0, 'data' => '分享人电话不能为空'];
//                };
//                //会员表
//                $UserModel = new Members();
//                //判断分享人是否存在
//                $referrer = $UserModel->where(['phone' => $data['referrer']])->first();
//                if (empty($referrer)) {
//                    return ['code' => 0, 'data' => '分享人不存在'];
//                }
//                //判断用户电话是否注册
//                $phone = $UserModel->where(['phone' => $data['phone']])->count();
//                if (!empty($phone)) {
//                    return ['code' => 0, 'data' => '电话已被注册'];
//                }
//                //微商城设置
//                $microMall = new MicroMall();
//                $micro = $microMall->orderBy('sorting')->first();
//                //超级商城设置
//                $ExceedShopModel = new ExceedShop();
//                $ExceedShop = $ExceedShopModel->get()->toArray();
//                $random = RANDOM(); //秘钥
//                $memberData = [
//                    'name' => $data['phone'],
//                    'user_name' => $data['name'],
//                    'phone' => $data['phone'],
//                    'password_pay' => ENCRYPTION(empty($data['password_pay']) ? $data['phone'] : $data['password_pay'], $random),
//                    'password' => ENCRYPTION(empty($data['password']) ? $data['phone'] : $data['password'], $random),
//                    'salting_pay' => $random,
//                    'salting' => $random,
//                    'enroll_time' => time(), //注册时间
//                    'activation_time' => time(), //激活时间
//                    'registered' => 1, //1 已激活 0 未激活
////            'company_id' => $company_id, //公司id
//                    'tiny_level' => $micro['id'],
//                    'referrer' => $referrer['uid'], //分享人
//                    'straight_shop_isdown' => $referrer['straight_shop_isdown'], //直商城开关 1开 2关
//                    'feferrer_name' => $data['user_name'], //分享人姓名
//                    'tiny_level_name' => $micro['vip_name'],
//                    'aisle' => 1, // 1 报单商城
//                    'super_level' => 1, //报单商城等级
//                    'super_level_name' => $ExceedShop[0]['vip_name'], //报单商城等级 名称
//                    'stores_number' => 0, //门店中心编号
//                    'updated_at' => date('Y-m-d H:i:s'),
//                    'created_at' => date('Y-m-d H:i:s')
//                ];
//                $member = $UserModel->create($memberData);
//                if (empty($member)) {
//                    DB::rollback();  //回滚
//                    return ['code' => 0, 'data' => '注册失败,重新注册'];
//                }else{
//                    return ['code' => 1, 'data' => '注册成功，即可登录'];
//                }
//                break;
//
//        }
    }

    /**
     * 现场活动信息录入
     */
    public function information()
    {

        return view('Home/login/information');
    }

    /**
     * 现场活动信息录入
     */
    public function InformationEntry(Request $request)
    {
        $FieldActivitiesModel = new FieldActivities();
        $data = $request->all();
        $user = $FieldActivitiesModel->where('phone', $data['phone'])->count();
        if ($user) {
            return ['code' => 0, 'data' => '此账号已提交,请勿重复提交'];
        }
        //判断联系人
        if (empty($data['phone'])) {
            return ['code' => 0, 'data' => '联系人电话不能为空'];
        };
        //判断联系人姓名
        if (empty($data['name'])) {
            return ['code' => 0, 'data' => '联系人姓名不能为空'];
        };
        // 检测手机号格式
        if (!preg_match('/^1[3456789]\d{9}$/', $data['phone'])) {
            return ['code' => 0, 'data' => '请填写正确的手机号'];
        }
        //判断分享人电话
        if (empty($data['sharer_name'])) {
            return ['code' => 0, 'data' => '分享人姓名不能为空'];
        };
        //收货地址
        if (empty($data['province'])) {
            return ['code' => 0, 'data' => '收货地址不能为空'];
        };
        //判断分享人电话
        if (empty($data['city'])) {
            return ['code' => 0, 'data' => '收货地址不能为空'];
        };
        if (empty($data['district'])) {
            return ['code' => 0, 'data' => '收货地址不能为空'];
        };
        if (empty($data['consignee_adr'])) {
            return ['code' => 0, 'data' => '收货地址不能为空'];
        };
        $informationData = [
            'phone' => $data['phone'],
            'name' => $data['name'],
            'sharer_phone' => $data['sharer_phone'],
            'sharer_name' => $data['sharer_name'],
            'consignee_adr' => $data['province'] . $data['city'] . $data['district'] . $data['consignee_adr'],
            'activity_type' => $data['activity_type'],
            'createtime' => time(),
        ];
        $member = $FieldActivitiesModel->create($informationData);
        if ($member) {
            return ['code' => 1, 'data' => '提交成功,等待发货'];
        } else {
            return ['code' => 0, 'data' => '提交失败'];
        }
    }

    /**
     * 信息提交成功页面
     */
    public function success()
    {

        return view('Home/login/success');
    }

    /**
     * 忘记密码
     */
    public function forgetPassword()
    {

        return view('Home/login/forgetPassword');
    }

    /**
     * 忘记密码验证码
     */
    public function yzx(Request $request)
    {
        $phone = $request->get('name');
        if (session('sms' . $phone)['time'] > time()) return ['code' => 0, 'data' => '请一分钟后重试'];
        $sms = sms($phone, 579897);
        if (!empty($sms['code'])) {
            return ['code' => 1, 'data' => '获取验证码成功'];
        }
        return ['code' => 0, 'data' => $sms['data']];
    }
}